﻿using System;
using TestingConcurrencyBenchmark.Helpers;

namespace TestingConcurrencyBenchmark.Problems.ReadersWriters
{
    internal class ReaderWriterWithDataRace : IReaderWriter
    {
        private readonly LightSwitch _readerSwitch;
        private readonly BenchmarkSemaphore _roomEmpty;
        private readonly LightSwitch _writerSwitch;

        public ReaderWriterWithDataRace()
        {
            _readerSwitch = new LightSwitch();
            _writerSwitch = new LightSwitch();
            _roomEmpty = new BenchmarkSemaphore(1);
        }

        #region IReaderWriter Members

        public void Write(Action action)
        {
            _writerSwitch.Lock(_roomEmpty);
            action();
            _writerSwitch.Unlock(_roomEmpty);
        }

        public void Read(Action action)
        {
            _readerSwitch.Lock(_roomEmpty);
            action();
            _readerSwitch.Unlock(_roomEmpty);
        }

        #endregion
    }
}